from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist


class Notification(models.Model):
    recipient = models.ForeignKey(User, related_name='notifications', on_delete=models.CASCADE)
    sender = models.CharField(max_length=255, blank=True, null=True)
    message = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    is_read = models.BooleanField(default=False)

    def __str__(self):
        return f'Notification for {self.recipient.username} from {self.sender}'

    class Meta:
        ordering = ['-timestamp']

    @classmethod
    def create_notification(cls, sender, user_id, message):
        try:
            user = User.objects.get(id=user_id)
            notification = cls.objects.create(recipient=user, sender=sender, message=message)
            return notification
        except ObjectDoesNotExist:
            raise ValueError(f"No user found with ID {user_id}")
